package com.zenchn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zenchn.annotation.OperLog;
import com.zenchn.entity.CustomerUpgradeVO;
import com.zenchn.entity.CustomerVisitVO;
import com.zenchn.entity.HttpDataResult;
import com.zenchn.enums.CustomerTypeEnum;
import com.zenchn.enums.OperLogActionEnum;
import com.zenchn.enums.RegionEnum;
import com.zenchn.enums.SessionAttributeEnum;
import com.zenchn.exception.CustomException;
import com.zenchn.model.*;
import com.zenchn.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拜访记录管理控制器
 *
 * @author panbingqi
 * @date 2021-06-04 17:34
 */
@RestController
@RequestMapping(value = "customerVisitWeb")
@Api(value = "拜访记录管理模块相关接口", tags = "信息管理-拜访记录信息管理")
@RequiresPermissions("visit:record")
public class CustomerVisitWebController {
    private final String MODULE = "信息管理>拜访记录信息管理";

    @Resource
    private CustomerVisitService customerVisitService;

    @Resource
    private CustomerService customerService;

    @Resource
    private RegionDetailService regionDetailService;

    @Resource
    private RegionService regionService;

    @Resource
    private AreasService areasService;

    @Resource
    private AccountService accountService;

    @Resource
    private CustomerContactsService customerContactsService;


    /**
     * 分页获取拜访记录信息管理列表
     *
     * @param keyword
     * @param regionId
     * @param areasCode
     * @param customerType
     * @param accountId
     * @param operatorId
     * @param startTime
     * @param endTime
     * @param page
     * @param pageSize
     * @param request
     * @param response
     * @return
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "分页获取拜访记录信息管理列表")
    @ApiOperation(value = "分页获取拜访记录信息管理列表", notes = "分页获取拜访记录信息管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "关键字"),
            @ApiImplicitParam(dataType = "String", name = "regionId", value = "所属大区"),
            @ApiImplicitParam(dataType = "String", name = "areasCode", value = "所属省份"),
            @ApiImplicitParam(dataType = "String", name = "customerType", value = "类型"),
            @ApiImplicitParam(dataType = "String", name = "accountId", value = "所属用户"),
            @ApiImplicitParam(dataType = "String", name = "operatorId", value = "操作人"),
            @ApiImplicitParam(dataType = "Date", name = "startTime", value = "参数名称，转移开始时间"),
            @ApiImplicitParam(dataType = "Date", name = "endTime", value = "参数名称，转移结束时间"),
            @ApiImplicitParam(dataType = "Integer", name = "page", value = "当前第page页"),
            @ApiImplicitParam(dataType = "Integer", name = "pageSize", value = "每页pageSize数量")
    })
    @GetMapping(value = "/list")
    @RequiresPermissions("visit:record")
    public ResponseEntity<HttpDataResult<PageInfo>> list(
            @RequestParam(required = false, value = "keyword") String keyword,
            @RequestParam(required = false, value = "regionId") String regionId,
            @RequestParam(required = false, value = "areasCode") String areasCode,
            @RequestParam(required = false, value = "customerType") String customerType,
            @RequestParam(required = false, value = "accountId") String accountId,
            @RequestParam(required = false, value = "operatorId") String operatorId,
            @RequestParam(required = false, value = "startTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
            @RequestParam(required = false, value = "endTime") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
            @RequestParam(required = false, value = "page", defaultValue = "1") Integer page,
            @RequestParam(required = false, value = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpDataResult<PageInfo> result = new HttpDataResult<>(request.getRequestURI());

        final TMiAccountExtend accountExtend = (TMiAccountExtend) request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        if (accountExtend == null) {
            throw new CustomException("当前登入账户无数据权限");
        }
        //获取当前登入用户所属省份数据权限
        List<String> areasCodeList = new ArrayList<>();
        if (accountExtend.getRegionCode() != null && !"".equals(accountExtend.getRegionCode().trim())) {
            areasCodeList = getAreasCodeList(accountExtend.getRegionCode().trim());
        }
        if (accountExtend.getAreasCode() != null && !"".equals(accountExtend.getAreasCode()) && !areasCodeList.contains(accountExtend.getAreasCode())) {
            areasCodeList.add(accountExtend.getAreasCode().trim());
        }
        //取交集
        List<String> resultList = new ArrayList<>();
        if (regionId != null && !"".equals(regionId.trim())) {
            List<String> codeList = getAreasCodeList(regionId);
            for (String code : areasCodeList) {
                if (codeList.contains(code)) {
                    resultList.add(code);
                }
            }
        } else {
            resultList.addAll(areasCodeList);
        }

        if (resultList.isEmpty()) {
            result.setData(new PageInfo());
        } else {
            PageHelper.startPage(page, pageSize);
            PageInfo pageInfo = new PageInfo(customerVisitService.selectDynamicSqlByParameter(keyword, resultList, areasCode, accountId, operatorId, customerType, startTime, endTime));

            List<TMiCustomerVisit> customerVisitList = pageInfo.getList();
            List<CustomerVisitVO> customerVisitVOList = new ArrayList<>();
            for (TMiCustomerVisit customerVisit : customerVisitList) {
                CustomerVisitVO customerVisitVO = new CustomerVisitVO();
                BeanUtils.copyProperties(customerVisit, customerVisitVO);

                TMiCustomer customer = customerService.selectByPrimaryKey(customerVisit.getCustomerId());
                if (customer != null) {
                    //设置区域名称
                    TMiRegionDetailExample regionDetailExample = new TMiRegionDetailExample();
                    regionDetailExample.createCriteria().andAreasCodeEqualTo(customer.getAreasCode()).andRegionIdNotEqualTo(RegionEnum.NATIONAL_ADMINISTRATIVE_REGION.getId());

                    List<String> regionIdList = regionDetailService.selectByExample(regionDetailExample).stream().map(TMiRegionDetail::getRegionId).collect(Collectors.toList());
                    if (regionIdList != null && !regionIdList.isEmpty()) {
                        TMiRegionExample regionExample = new TMiRegionExample();
                        regionExample.createCriteria().andRegionIdIn(regionIdList);

                        customerVisitVO.setRegionName(regionService.selectByExample(regionExample).stream().map(TMiRegion::getRegionName).collect(Collectors.joining(",")));
                    }
                    //设置省级名称
                    TSysAreas areas = areasService.selectByPrimaryKey(customer.getAreasCode());
                    if (areas != null) {
                        customerVisitVO.setAreasCodeName(areas.getName());
                    }
                    //设置客户类型名称
                    customerVisitVO.setCustomerTypeName(CustomerTypeEnum.getAppDesc(customer.getCustomerType()));
                    //设置所属用户名称
                    TSysAccount account = accountService.selectByPrimaryKey(customer.getAccountId());
                    if (account != null) {
                        customerVisitVO.setAccountName(account.getRealName());
                    }
                    //设置客户名称
                    customerVisitVO.setCustomerName(customer.getCustomerName());
                }
                //设置拜访人名称
                TSysAccount account = accountService.selectByPrimaryKey(customerVisit.getCreator());
                if (account != null) {
                    customerVisitVO.setOperatorName(account.getRealName());
                }

                TMiCustomerContacts customerContacts = customerContactsService.selectByPrimaryKey(customerVisit.getContactsId());
                if (customerContacts != null) {
                    //设置被拜访人电话
                    customerVisitVO.setVisitTel(customerContacts.getTelephone());
                    //设置被拜访人职务
                    customerVisitVO.setPost(customerContacts.getPost());
                    //设置被拜访人名称
                    customerVisitVO.setVisitName(customerContacts.getContactsName());
                }
                customerVisitVOList.add(customerVisitVO);
            }
            pageInfo.setList(customerVisitVOList);

            result.setData(pageInfo);
        }

        result.setMessage("获取拜访记录信息管理列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 获取省份信息
     *
     * @param regionId
     * @return
     */
    private List<String> getAreasCodeList(String regionId) {
        List<String> areasCodeList = new ArrayList<>();
        TMiRegionDetailExample regionDetailExample = new TMiRegionDetailExample();
        regionDetailExample.createCriteria().andRegionIdEqualTo(regionId);

        List<TMiRegionDetail> regionDetailList = regionDetailService.selectByExample(regionDetailExample);
        if (regionDetailList != null && !regionDetailList.isEmpty()) {
            areasCodeList.addAll(regionDetailList.stream().map(TMiRegionDetail::getAreasCode).collect(Collectors.toList()));
        }
        return areasCodeList;
    }

}

